package db

import (
	"matrix/backend/db/mysql"
	"time"
)

// Login : 用户登录
func Login(userName, userPwd string) (string, string, int8) {
	var token string
	var times string
	var status int8 = 0
	sql := "select user_name, user_pwd, last_active, user_token from tbl_user where user_name=?"
	rows, _ := mysql.DBConn().Query(sql, userName)
	for rows.Next() {
		var username string
		var userpwd string
		var lastime string
		var usertoken string
		// 获取查询结果
		err := rows.Scan(&username, &userpwd, &lastime, &usertoken)
		if err != nil {
			status = 1
		}
		if userName != username || userPwd != userpwd {
			status = 2
		}
		times = lastime
		timenow := time.Now().Format("2006-01-02 15:04:05")

		// 更新时间戳
		sql = "update tbl_user set last_active=? where user_name=?"
		stmt, _ := mysql.DBConn().Prepare(sql)
		result, err := stmt.Exec(timenow, userName)
		if err != nil {
			status = 3
		}
		affect, _ := result.RowsAffected()
		// 查看是否更新成功
		if affect == 0 {
			status = 4
		}
		if status == 0 {
			token = usertoken
		}
	}
	if token == "" {
		status = 5
	}
	// 查询token,返回toke
	return token, times, status
}
